﻿using System;
using System.Collections.Generic;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Views;
using Xamarin.ActionbarSherlockBinding.App;
using Cinemacenter.Shared;

namespace Cinemacenter.Droid
{
	public class CitiesFragment : SherlockFragment, CitiesDialogFragment.ICitiesDialogFragmentListener
	{
		int locationId;
		long citiesTsvt;
		Xamarin.ActionbarSherlockBinding.App.ActionBar actionBar;
		CityCollection citiesCollection;
		ICitiesFragmentCallbacks mCallbacks;

		public interface ICitiesFragmentCallbacks
		{
			void NotifyOnCityChanged (int locationId);

			void NotifyOnCitiesLoaded (CityCollection dataset);

			void NotifyOnCitiesLoadFailed ();

			void NotifyOnCityUnchanged ();
		}

		public override void OnAttach (Activity activity)
		{
			actionBar = ((SherlockFragmentActivity)activity).SupportActionBar;
			base.OnAttach (activity);
		}

		public static CitiesFragment Instance (int locationId, long citiesTsvt)
		{
			var f = new CitiesFragment ();
			var args = new Bundle ();
			args.PutInt ("locationId", locationId);
			args.PutLong ("citiesTsvt", citiesTsvt);
			f.Arguments = args;
			return f;
		}

		public override void OnActivityCreated (Bundle savedInstanceState)
		{
			base.OnActivityCreated (savedInstanceState);
			RetainInstance = true;
		}

		public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
		{
			locationId = Arguments.GetInt ("locationId");
			citiesTsvt = Arguments.GetLong ("citiesTsvt");
			GetData ();
			return base.OnCreateView (inflater, container, savedInstanceState);	
		}

		async void GetData ()
		{
			long unixTime = new DateTime ().CurrentTimeMillis () / 1000L;
			citiesCollection = new CityCollection (); 
			citiesCollection.Cities = DBHelper.GetCities ();
			if (unixTime > citiesTsvt || citiesCollection.Cities.Count == 0) {
				using (var progress = new ProgressDialog (Activity)) {
					View empty = Activity.FindViewById (Resource.Id.emptyRecords);
					empty.Visibility = ViewStates.Invisible;
					progress.SetMessage (GetString (Resource.String.loading));
					progress.SetTitle (actionBar.Title);
					progress.SetCanceledOnTouchOutside (false);
					progress.Show ();
					citiesCollection = await WebService.Shared.GetCities ();
					if (citiesCollection.Cities == null) {
						citiesCollection.Cities = new List<City> ();
						mCallbacks.NotifyOnCitiesLoadFailed ();
						citiesCollection.Cities = DBHelper.GetCities ();
					} else {
						mCallbacks.NotifyOnCitiesLoaded (citiesCollection);
						DBHelper.DeleteCities ();
						DBHelper.SaveCities (citiesCollection.Cities);
					}
					progress.Dismiss ();
				}
			}
			if (citiesCollection.Cities.Count > 0)
				ShowCitiesDialog ();
		}

		void ShowCitiesDialog ()
		{
			var cs_cities = new string[citiesCollection.Cities.Count];
			int selectedIndex = -1;
			for (int i = 0; i < citiesCollection.Cities.Count; i++) {
				cs_cities [i] = citiesCollection.Cities [i].Name;
				if (locationId == int.Parse (citiesCollection.Cities [i].CityId))
					selectedIndex = i;
			}
			var dialog = (CitiesDialogFragment)FragmentManager.FindFragmentByTag ("CITIES_DIALOG");
			if (dialog != null) {
				dialog.Dispose ();
			}
			dialog = CitiesDialogFragment.Instance (cs_cities, selectedIndex);
			dialog.Listener = this;
			var mFragmentTransaction = FragmentManager.BeginTransaction ();
			mFragmentTransaction.Add (dialog, "CITIES_DIALOG");
			mFragmentTransaction.CommitAllowingStateLoss ();
		}

		#region ICitiesDialogFragmentListener implementation

		public void OnNegativeButtonClick (IDialogInterface dialog, int id)
		{
			var d = (CitiesDialogFragment)FragmentManager.FindFragmentByTag ("CITIES_DIALOG");
			if (d != null) {
				FragmentManager.BeginTransaction ().Remove (d).Commit ();
			}
			mCallbacks.NotifyOnCityUnchanged ();
		}

		public void OnItemClick (IDialogInterface dialog, int item)
		{
			mCallbacks.NotifyOnCityChanged (int.Parse (citiesCollection.Cities [item].CityId));
			if (dialog != null)
				dialog.Dismiss ();
		}

		#endregion

		public ICitiesFragmentCallbacks ActivityCallbacks {
			set {
				mCallbacks = value;
			}
		}
	}
}
 